package com.health.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.health.domain.dto.LoginDTO;
import com.health.domain.pojo.User;
import com.health.mapper.UserMapper;
import com.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-06-20 19:42
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     *
     * @param loginDTO 登录请求参数
     * @return 用户信息
     */
    @Override
    public User login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        if(StrUtil.isBlank(username)
            || StrUtil.isBlank(password)) {
            throw new RuntimeException("用户名密码都不能为空");
        }
        // 1.根据用户名查询t_user表
        // select * from t_user where username = ?
        User user = userMapper.selectByUsername(username);
        // 2.判断用户信息是否合理
        if(ObjUtil.isNull(user)) {
            throw new RuntimeException("用户不存在，请联系管理员！");
        }
        // 把前端传递过来的密码进行加密后，再与数据库密码进行比较
        String pwd = DigestUtil.md5Hex(password);
        if (!StrUtil.equals(pwd, user.getPassword())) {
            throw new RuntimeException("密码错误！");
        }
        return user;
    }



}
